package com.nut.lmsc.util;

import com.nut.lmsc.common.Constants;
import com.nut.lmsc.redis.RedisKeys;
import com.nut.lmsc.enums.IdTagEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@Component
public class IdUtil {

    public static final String DATE_YYMMDDHHMMSS = "yyMMddHHmmss";
    public static final String DIGIT4 = "%04d";
    public static final String DIGIT3 = "%03d";

    public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(DATE_YYMMDDHHMMSS);

    public static Long getMemberId() {
        String str = FORMATTER.format(LocalDateTime.now()) + (100 + ThreadLocalRandom.current().nextInt(899));
        return Long.valueOf(str);
    }

    public static String generateSsn() {
        return FORMATTER.format(LocalDateTime.now()) + (100 + ThreadLocalRandom.current().nextInt(899));
    }

    public static Long generatedCommonId(IdTagEnum idTagEnum) {
        String prefix = RedisKeys.getPrefixKey(idTagEnum);

        String activeProfile = SpringUtil.getActiveProfile();
        if (Constants.DEV.equals(activeProfile)) {
            prefix = "9" + prefix.substring(1);
        }

        RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate", RedisTemplate.class);
        Long increment = redisTemplate.opsForValue().increment(prefix);
        // 对KEY添加过期时间
        redisTemplate.opsForValue().set(prefix, increment, 3, TimeUnit.DAYS);

        StringBuilder sb = new StringBuilder();
        sb.append(prefix);
        //最多1W笔订单
        if (increment.toString().length() < 5) {
            sb.append(String.format(DIGIT4, increment));
        } else {
            sb.append(increment);
        }
        return Long.valueOf(sb.toString());
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static void main(String[] args) {

        System.out.println(String.format(DIGIT4, 22));
        System.out.println(String.format(DIGIT4, 1));

    }
}
